package thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * date: 2023-2-16
 * 创建两个线程作为：生产者和消费者
 */
public class ThreadDemo22 {
    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingDeque<>(); // BlockingQueue是阻塞队列

        Thread customer = new Thread(() -> {
            while (true) {
                Integer result = null;
                try {
                    result = blockingQueue.take(); // 取元素
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费元素：" + result);
            }
        });
        customer.start();

        Thread producer = new Thread(() -> {
            int count = 0;
            while (true) {
                try {
                    blockingQueue.put(count); // 投放元素
                    System.out.println("生产元素：" + count);
                    count++; // 元素的数量
                    Thread.sleep(500); // 表示每隔500ms就生产一个新的元素
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();
    }
}
